import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad

# 中文和负号正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

def darboux_sum_analysis(func, interval, num_partitions):
    """分析和可视化达布上和与下和随划分细化变化"""
    a, b = interval
    partitions = [2**i for i in range(1, num_partitions+1)]
    
    upper_sums = []; lower_sums = []; differences = []
    
    for n in partitions:
        x = np.linspace(a, b, n+1)
        dx = (b - a) / n
        upper_sum = 0; lower_sum = 0
        
        for i in range(n):
            segment = np.linspace(x[i], x[i+1], 100)
            func_vals = func(segment)
            M_i = np.max(func_vals)  # 上确界近似
            m_i = np.min(func_vals)  # 下确界近似
            upper_sum += M_i * dx
            lower_sum += m_i * dx
        
        upper_sums.append(upper_sum)
        lower_sums.append(lower_sum)
        differences.append(upper_sum - lower_sum)
    
    # 可视化结果
    plt.figure(figsize=(15, 5))
    
    plt.subplot(1, 3, 1)
    plt.plot(partitions, upper_sums, 'ro-', label='达布上和 S(P)')
    plt.plot(partitions, lower_sums, 'bo-', label='达布下和 s(P)')
    plt.xlabel('划分细度 n'); plt.ylabel('和的值')
    plt.title('达布上和与下和随划分细化变化'); plt.legend(); plt.grid(True, alpha=0.3)
    
    plt.subplot(1, 3, 2)
    plt.plot(partitions, differences, 'go-')
    plt.xlabel('划分细度 n'); plt.ylabel('S(P) - s(P)')
    plt.title('达布和差值的收敛性'); plt.grid(True, alpha=0.3)
    
    plt.subplot(1, 3, 3)
    true_integral, _ = quad(func, a, b)
    plt.axhline(y=true_integral, color='purple', linestyle='--', 
                label=f'真实积分值: {true_integral:.6f}')
    plt.plot(partitions, upper_sums, 'ro-', label='达布上和')
    plt.plot(partitions, lower_sums, 'bo-', label='达布下和')
    plt.xlabel('划分细度 n'); plt.ylabel('积分值')
    plt.title('达布和与真实积分值的逼近'); plt.legend(); plt.grid(True, alpha=0.3)
    
    plt.tight_layout()
    plt.show()
    
    print("达布和差值收敛分析:")
    for i, n in enumerate(partitions):
        print(f"划分数: {n}, 上和-下和 = {differences[i]:.6f}")

print("连续函数的达布和分析:")
darboux_sum_analysis(lambda x: x**2, [0, 1], 6)